window.onload=function () {
	waterfall('main','box');
	var dataInt={
		"data":
			[
				{"src":"1.jpg"},
				{"src":"2.jpg"},
				{"src":"3.jpg"},
				{"src":"4.jpg"},
				{"src":"5.jpg"},
				{"src":"6.jpg"}
			]
	}
	window.onscroll=function () {
		checkScrollSlide();
		if(checkScrollSlide){
			var oParent=document.getElementById('main');
			for(var i=0;i<dataInt.data.length;i++){
				var oBox=document.createElement('div');
				var oPic=document.createElement('div');
				oBox.className="box";
				oPic.className="pic";
				oParent.appendChild(oBox);
				oBox.appendChild(oPic);

				var oImg=document.createElement('img');
				oImg.src="images/"+dataInt.data[i].src;

				oPic.appendChild(oImg);
			}
		}
		waterfall('main','box');
	}
}


function waterfall(parent,child) {
	//将main下面所有class为box的元素取出来
	var oParent=document.getElementById(parent);
	var oBoxs=getByClass(oParent,child);
	// 计算整个页面的列数（页面宽/box宽）
	var oBoxWidth=oBoxs[0].offsetWidth;
	var cols=Math.floor(document.documentElement.clientWidth/oBoxWidth);
	//设置main的宽度
	oParent.style.cssText='width:'+oBoxWidth*cols+'px';

	var hArr=[];//存放每一列高度的数组
	for(var i=0;i<oBoxs.length;i++){
		if(i<cols){
			hArr.push(oBoxs[i].offsetHeight);
		}else{
			//Math.min不能放入数组，利用apply()改变this的指向
			var minH=Math.min.apply(null,hArr);
			var index=getMinHindex(hArr,minH);
			oBoxs[i].style.position="absolute";
			oBoxs[i].style.top=minH+"px";
			// oBoxs[i].style.left=oBoxs*index+"px";
			oBoxs[i].style.left=oBoxs[index].offsetLeft+'px';
			hArr[index]+=oBoxs[i].offsetHeight;
		}
	}
}


function getByClass(parent,className) {
	var boxArr=new Array();
	var oElements=parent.getElementsByTagName('*');
	for(var i=0;i<oElements.length;i++){
		if(oElements[i].className==className){
			boxArr.push(oElements[i]);
		}
	}
	return boxArr;
}

function getMinHindex(arr,value) {
	for(var i in arr){
		if(arr[i]==value){
			return i;
		}
	}
}

function checkScrollSlide() {
	var oParent=document.getElementById("main");
	var oBoxs=getByClass(oParent,'box');
	var lastBoxH=oBoxs[oBoxs.length-1].offsetTop+Math.floor(oBoxs[oBoxs.length-1].offsetHeight);
	//滚动高度
	var scrollTop=document.body.scrollTop||document.documentElement.scrollTop;
	//当前页面高度
	var height=document.body.clientHeight||document.documentElement.clientHeight;
	console.log(lastBoxH);
	console.error(scrollTop);
	console.log(height);
	return (lastBoxH<scrollTop+height)?true:false;
}